package edu.unindra.raport.gui;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;

import edu.unindra.raport.dao.entity.Nilai;
import edu.unindra.raport.dao.impl.NilaiImpl;
import edu.unindra.raport.model.TabelModelNilai;
import edu.unindra.raport.template.ViewPortGlass;
import usu.widget.ButtonGlass;
import usu.widget.Panel;
import usu.widget.util.WidgetUtilities;

import javax.swing.GroupLayout.Alignment;
import javax.swing.GroupLayout;
import javax.swing.JOptionPane;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.SwingWorker;

import java.awt.Color;
import java.awt.Font;

public class FormDetailMenuNilai extends Panel {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private TabelModelNilai modelTable;
	private JTable table;

	private ButtonGlass btnAdd;
	private ButtonGlass btnDelete;
	private ButtonGlass btnEdit;

	private ViewPortGlass viewPort;
	private JScrollPane scrollPane;

	private NilaiImpl siImpl = null;
	private FormDetailMenuNilaiAdd fDetailSiAdd = null;
	private FormDetailMenuNilaiEdit fDetailSiEdit = null;
	private ExecutorService executor;

	private String s;
	private String t;
	private String u;
	private String v;
	private int i;

	public FormDetailMenuNilai() {
		modelTable = new TabelModelNilai();

		executor = Executors.newCachedThreadPool();
		siImpl = new NilaiImpl();

		initComponents();
		initFinals();

		/** load data operator ke dalam table. */
		new LoadDataNilaiSiswa().execute();
	}

	/**
	 * 
	 * @return
	 */
	public TabelModelNilai getModelTable() {
		return modelTable;
	}

	/**
	 * 
	 * @return
	 */
	public JTable getTable() {
		return table;
	}

	private void initComponents() {
		scrollPane = new JScrollPane();
		viewPort = new ViewPortGlass();
		table = new JTable();

		btnAdd = new ButtonGlass();
		btnAdd.setFont(new Font("Tahoma", Font.BOLD, 11));
		btnDelete = new ButtonGlass();
		btnDelete.setFont(new Font("Tahoma", Font.BOLD, 11));
		btnEdit = new ButtonGlass();
		btnEdit.setFont(new Font("Tahoma", Font.BOLD, 11));

		viewPort.setView(table);

		table.setAutoCreateRowSorter(true);
		table.setForeground(Color.BLACK);
		table.setToolTipText("Tabel Operator");
		table.setFillsViewportHeight(true);
		table.setOpaque(false);
		table.setSelectionBackground(new java.awt.Color(51, 255, 52));
		table.setSelectionForeground(new java.awt.Color(0, 0, 0));

		setOpaque(false);
		setOpaqueGradient(false);
		setOpaqueImage(false);

		scrollPane.setBorder(javax.swing.BorderFactory
				.createLineBorder(new java.awt.Color(0, 0, 0)));
		scrollPane.setOpaque(false);
		scrollPane.setViewport(viewPort);

		btnDelete.setMnemonic('H');
		btnDelete.setText("Hapus");
		btnDelete.setToolTipText("Klik untuk menghapus operator");
		btnDelete.setRoundRect(true);

		btnEdit.setMnemonic('U');
		btnEdit.setText("Ubah");
		btnEdit.setToolTipText("Klik untuk mengubah operator");
		btnEdit.setRoundRect(true);

		btnAdd.setMnemonic('A');
		btnAdd.setText("Tambah");
		btnAdd.setToolTipText("Klik untuk menambah operator");
		btnAdd.setRoundRect(true);

		btnDelete.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				btnDeleteActionPerformed(e);
			}
		});

		btnEdit.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				btnEditActionPerformed(e);
			}
		});

		btnAdd.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				btnAddActionPerformed(e);
			}
		});

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
		layout.setHorizontalGroup(layout
				.createParallelGroup(Alignment.TRAILING)
				.addGroup(
						layout.createSequentialGroup()
								.addContainerGap()
								.addGroup(
										layout.createParallelGroup(
												Alignment.TRAILING)
												.addComponent(
														scrollPane,
														Alignment.LEADING,
														GroupLayout.DEFAULT_SIZE,
														430, Short.MAX_VALUE)
												.addGroup(
														layout.createSequentialGroup()
																.addComponent(
																		btnAdd,
																		GroupLayout.PREFERRED_SIZE,
																		GroupLayout.DEFAULT_SIZE,
																		GroupLayout.PREFERRED_SIZE)
																.addPreferredGap(
																		ComponentPlacement.RELATED)
																.addComponent(
																		btnEdit,
																		GroupLayout.PREFERRED_SIZE,
																		GroupLayout.DEFAULT_SIZE,
																		GroupLayout.PREFERRED_SIZE)
																.addPreferredGap(
																		ComponentPlacement.RELATED)
																.addComponent(
																		btnDelete,
																		GroupLayout.PREFERRED_SIZE,
																		GroupLayout.DEFAULT_SIZE,
																		GroupLayout.PREFERRED_SIZE)))
								.addContainerGap()));
		layout.setVerticalGroup(layout
				.createParallelGroup(Alignment.TRAILING)
				.addGroup(
						layout.createSequentialGroup()
								.addContainerGap()
								.addComponent(scrollPane,
										GroupLayout.DEFAULT_SIZE, 237,
										Short.MAX_VALUE)
								.addGap(18)
								.addGroup(
										layout.createParallelGroup(
												Alignment.BASELINE)
												.addComponent(
														btnDelete,
														GroupLayout.PREFERRED_SIZE,
														GroupLayout.DEFAULT_SIZE,
														GroupLayout.PREFERRED_SIZE)
												.addComponent(
														btnEdit,
														GroupLayout.PREFERRED_SIZE,
														GroupLayout.DEFAULT_SIZE,
														GroupLayout.PREFERRED_SIZE)
												.addComponent(
														btnAdd,
														GroupLayout.PREFERRED_SIZE,
														GroupLayout.DEFAULT_SIZE,
														GroupLayout.PREFERRED_SIZE))
								.addContainerGap()));
		this.setLayout(layout);
	}

	protected void btnAddActionPerformed(ActionEvent e) {
		fDetailSiAdd = new FormDetailMenuNilaiAdd(this);
		fDetailSiAdd.setVisible(true);

	}

	protected void btnEditActionPerformed(ActionEvent e) {
		int i = 0;
		if (table.getSelectedRowCount() == 0) {
			return;
		}

		i = table.convertRowIndexToModel(table.getSelectedRow());
		Nilai empl = modelTable.getNilai(i);
		fDetailSiEdit = new FormDetailMenuNilaiEdit(this);
		fDetailSiEdit.setNilai(empl);
		fDetailSiEdit.setVisible(true);

	}

	protected void btnDeleteActionPerformed(ActionEvent e) {
		boolean b;

		i = getTable().getSelectedRowCount();

		if (i == 0) {
			return;
		}

		if (i > 1) {
			if (JOptionPane.showConfirmDialog(this,
					"Anda yakin akan menghapus " + i + " data siswa ?",
					"Hapus Data Siswa", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
				b = true;
			} else {
				b = false;
			}
		} else {
			if (JOptionPane.showConfirmDialog(this,
					"Anda yakin akan menghapus data siswa yang terseleksi?",
					"Hapus Data Siswa", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
				b = true;
			} else {
				b = false;
			}
		}

		if (b) {
			WidgetUtilities.invokeLater(new Runnable() {

				@Override
				public void run() {
					while (getTable().getSelectedRowCount() > 0) {
						i = getTable().convertRowIndexToModel(
								getTable().getSelectionModel()
										.getMaxSelectionIndex());

						s = getModelTable().getNilai(i).getNis();
						t = getModelTable().getNilai(i).getNip();
						u = getModelTable().getNilai(i).getThn_ajaran();
						v = getModelTable().getNilai(i).getKls();

						try {
							@SuppressWarnings("unused")
							int retVal = siImpl.delete(s, t, u, v);
						} catch (Exception e) {
							e.printStackTrace();
						}
						getModelTable().removeNilai(i);
					}

					getModelTable().fireTableDataChanged();
					getTable().revalidate();
				}
			});
		}

	}

	private void initFinals() {

		table.setModel(modelTable);
		table.getTableHeader().setReorderingAllowed(false);
		WidgetUtilities.setAutomaticPopUpMenu(table);
		for (int i = 0; i < table.getColumnCount(); i++) {
			table.getColumnModel().getColumn(i)
					.setCellRenderer(new RenderTable());
		}
	}

	public static class RenderTable extends DefaultTableCellRenderer {

		private static final long serialVersionUID = -1;

		@Override
		public Component getTableCellRendererComponent(JTable table,
				Object value, boolean isSelected, boolean hasFocus, int row,
				int column) {
			if (value != null) {
				setToolTipText(value.toString());
				setOpaque(isSelected);
				return super.getTableCellRendererComponent(table, value,
						isSelected, hasFocus, row, column);
			} else {
				return super.getTableCellRendererComponent(table, value,
						isSelected, hasFocus, row, column);
			}
		}
	}

	public class LoadDataNilaiSiswa extends SwingWorker<List<Nilai>, String> {
		public LoadDataNilaiSiswa() {
			getModelTable().removeAllElements();
		}

		@Override
		protected List<Nilai> doInBackground() throws Exception {
			ArrayList<Nilai> array = new ArrayList<Nilai>();

			List<Nilai> o = siImpl.getNilaiAll();
			for (Nilai si : o) {
				array.add(si);
			}
			return array;
		}

		@Override
		protected void done() {
			executor.execute(new Runnable() {

				public void run() {
					try {
						getModelTable().add(get());
					} catch (InterruptedException ex) {
						ex.getStackTrace();
					} catch (ExecutionException ex) {
						ex.getStackTrace();
					} finally {
						table.revalidate();
						table.repaint();
					}
				}
			});
		}
	}
}
